<template>
  <div class="login">
    <div class="bgimg"></div>
    <div class="popup">
      <h4>登录</h4>
      <van-cell-group :border="false">
        <van-field placeholder="请输入用户昵称" :border="false" v-model="uname">
          <i class="iconfont icon-yonghu" slot="left-icon"></i>
        </van-field>
        <van-field
          placeholder="请输入登录密码"
          type="password"
          v-model="password"
        >
          <i class="iconfont icon-mima1" slot="left-icon"></i>
        </van-field>
        <van-button
          round
          block
          type="info"
          native-type="submit"
          @click="onSubmit"
          >登录</van-button
        >
      </van-cell-group>
      <div>
        <span @click="$router.push('/find')">忘记密码</span>
        <span @click="$router.push('/register')">注册</span>
      </div>
    </div>
    <div class="divider">
      <van-divider :style="{ color: '#757171', borderColor: '#b3b3b3' }">
        其他登录方式
      </van-divider>
    </div>
    <div>
      <i class="iconfont icon-qq"></i>
      <i class="iconfont icon-weibo"></i>
      <i class="iconfont icon-weixin"></i>
    </div>
  </div>
</template>

<script>
import { Toast } from "vant";
import { login } from "@/api/login";
export default {
  data() {
    return {
      uname: "",
      password: "",
    };
  },
  methods: {
    // 登录
    onSubmit() {
      if (!this.uname) {
        return Toast.fail({ message: "请输入用户昵称!" });
      }
      if (this.uname.length < 3 || this.uname.length > 6) {
        return Toast.fail({ message: "用户昵称输入不合法!" });
      }
      if (!this.password) {
        return Toast.fail({ message: "请输入密码!" });
      }
      if (this.password.length < 6 || this.password.length > 12) {
        return Toast.fail({ message: "密码格式不正确!" });
      }

      // 验证通过，发起请求校验密码
      login({
        uname: this.uname,
        password: this.password,
      }).then((res) => {
        console.log(res);
        console.log(res.data.status);
        if (res.data.status != 200) {
          return Toast.fail({ message: res.data.message });
        }
        // 将登录成功生成的token保存到localStorage中
        localStorage.setItem("token", res.data.token);
        // 将用户昵称，手机号，头像，uid保存到vuex中
        this.$store.commit("changeName", res.data.information.uname);
        this.$store.commit("changePhone", res.data.information.phone);
        this.$store.commit("changePic", res.data.information.pic);
        this.$store.commit("changeUid", res.data.information.uid);
        // 跳转到首页
        this.$router.push("/home");
        return Toast.success({ message: "登录成功!" });
      });
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .van-field__left-icon {
  color: #ffca0d;
  //   color: #b3b3b3;
}
</style>
